﻿//------------------------------------------------------------------------------------------------- 
// <copyright file="TofCanardpcAPI.cs" company="Elpaulo Productions">
//   Copyright (c) Elpaulo Productions. All rights reserved.
// </copyright>
//-------------------------------------------------------------------------------------------------
namespace Elpaulo.Canardpc.TofCanardpcAPI
{
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;

    using HtmlAgilityPack;
   
    /// <summary>
    /// Upload functions calls and getters for uploaded images URLs
    /// </summary>
    public static class TofCanardpcAPI
    {
        /// <summary>
        /// Image Upload. Needs refactoring
        /// </summary>
        /// <param name="url">URL de la page d'upload</param>
        /// <param name="file">Fichier à envoyer</param>
        /// <param name="paramName">Nom du champ fichier sur le formulaire web</param>
        /// <param name="contentType">Type d'image à envoyer</param>
        /// <param name="nvc">Paramètres optionnels</param>
        /// <returns>URL of the link page</returns>
        public static string UploadImage(string url, string file, string paramName, string contentType, NameValueCollection nvc)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
            byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
            httpWebRequest.Method = "POST";
            httpWebRequest.KeepAlive = true;
            httpWebRequest.ReadWriteTimeout = 60000;
            httpWebRequest.MaximumResponseHeadersLength = 65000;
            httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream stream = httpWebRequest.GetRequestStream();

            string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
            foreach (string key in nvc.Keys)
            {
                stream.Write(boundarybytes, 0, boundarybytes.Length);
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                stream.Write(formitembytes, 0, formitembytes.Length);
            }

            stream.Write(boundarybytes, 0, boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
            string header = string.Format(headerTemplate, paramName, file, contentType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            stream.Write(headerbytes, 0, headerbytes.Length);

            FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
            byte[] buffer = new byte[4096];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                stream.Write(buffer, 0, bytesRead);
            }

            fileStream.Close();

            byte[] trailer = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--\r\n", boundary));
            stream.Write(trailer, 0, trailer.Length);
            stream.Close();

            WebResponse webResponse = null;

            try
            {
                webResponse = httpWebRequest.GetResponse();
                Stream stream2 = webResponse.GetResponseStream();
                StreamReader reader2 = new StreamReader(stream2);

                string response = reader2.ReadToEnd();
                string urlUpload = response.Substring(43, response.Length - 45);

                return urlUpload;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error uploading file", ex);
                if (webResponse != null)
                {
                    webResponse.Close();
                    webResponse = null;
                }
            }
            finally
            {
                httpWebRequest = null;
            }

            return null;
        }

        public static ImageLinks ExtractLinksFromUrl(string linkPage)
        {
            // Downloading webpage
            WebClient webClient = new WebClient();
            string source = webClient.DownloadString(linkPage);
            webClient.Dispose();

            // Parsing html
            HtmlDocument htmlDocument = new HtmlDocument();
            htmlDocument.LoadHtml(source);

            // Getting input fields
            HtmlNodeCollection inputFields = htmlDocument.DocumentNode.SelectNodes("//input");

            // ImageLinks creation
            ImageLinks imageLinks = new ImageLinks();

            imageLinks.BBCode200 = inputFields[0].Attributes["value"].Value;
            imageLinks.BBCode600 = inputFields[1].Attributes["value"].Value;
            imageLinks.BBCodeFullSize = inputFields[2].Attributes["value"].Value;
            imageLinks.DirectLink = inputFields[3].Attributes["value"].Value;
            imageLinks.LinkPage = inputFields[4].Attributes["value"].Value;

            return imageLinks;
        }
    }
}
